import {applyMiddleware, createStore} from 'redux';
import thunk from 'redux-thunk';
import reducers from '../reducer';
import {navMiddleware} from '../navigator/AppNavigator';

/**
 * 自定义中间件，输出Redux日志
 * @param store
 * @returns {function(*): Function}
 */
const logger = store => next => action => {
  if (typeof action === 'function') {
    console.log('dispatching is a function');
  } else {
    console.log('dispatching', action);
  }
  // console.log('preState', store.getState());
  next(action); // 需要执行next，将action传递给下一个中间件，否则将不会再向下执行
  console.log('nextState', store.getState());
};

/**
 * 组合中间件
 * @type {*[]}
 */
const middlewares = [
  navMiddleware,
  logger, // 将日志中间件导入store
  thunk, // 异步action中间件
];

/**
 * 创建 store（一个Redux应用只有一个单一的store，拆分数据逻辑时，应使用reducer组合）
 */
export default createStore(reducers, applyMiddleware(...middlewares));